<template>
  <main-layout title="管理材料信息" :showHome="true">
    <ul class="product-list" @scroll="scrollEvt">
      <li class="list-item" v-for="item in list" :key="item.id">
        <span>{{ item.name }}</span>
        <span class="remark">{{ item.remark }}</span>
        <div class="icon">
          <i @click="tonewPage(item)"></i>
        </div>
      </li>
      <li>
        <span v-if="loading" class="more">加载中...</span>
        <span v-if="!loading && hasMore" class="more">向下滑动加载更多...</span>
        <span v-if="!loading && !hasMore" class="more"
          >不要再划了，木有了!</span
        >
      </li>
    </ul>
  </main-layout>
</template>
<script>
import { materialListApi } from "../../apis/PurchaseApi";
export default {
  data() {
    return {
      list: [],
      listObj: {
        name: "",
        page: 1,
        size: 5,
      },
      // 是否在加载中
      loading: true,
      // 定义为是否后端还有数据的标识
      hasMore: true,
    };
  },
  // 定义过滤器
  filters: {},
  created() {
    this.getList();
  },
  computed: {
    userRight() {
      return this.$store.getters["common/userRights"];
    },
  },
  methods: {
    scrollEvt(e) {
      // 是否已经滚动到底部
      let bottom =
        e.target.scrollHeight -
          e.target.offsetHeight -
          e.target.scrollTop -
          20 <
        0;
      if (bottom && this.hasMore && !this.loading) {
        // 将滑动状态改为true
        this.loading = true;
        // 加载下一页数据
        this.page += 1;
        // 调用数据请求方法
        this.getList();
      }
    },
    async getList() {
      let result = await materialListApi(this.listObj);
      if (result.code === 200) {
        this.list = this.list.concat(result.data.rows);
        // 计算hasMore的值：当前页树 * 每页展示的条数 要小于 后端总条数 才有更多数据，还没有从后端获取回来
        this.hasMore = this.page * this.size < result.data.total;
      }
      setTimeout(() => {
        this.loading = false;
      });
    },
    tonewPage(row) {
      // 判断是新增事件还是编辑事件
      let edit = !!row;
      // 判断是否有进去的权限
      let right = this.userRight.find((it) => it.id === "SYSTEM-01-01");
      if (!!right) {
        // 不是编辑按钮，且有进去的权限
        if (!edit && right.role.includes("C")) {
          this.$router.push({
            name: "editProduct",
            query: { from: "list" },
          });
        } else {
          // 是从编辑按钮过来
          if (!!edit) {
            // 判断是否有进去的权限
            if (right.role.includes("C")) {
              this.$router.push({
                name: "editProduct",
                query: { id: row.id, from: "list" },
                params: { row },
              });
            } else {
              this.$toast.fail("您没有访问的权限!");
            }
          } else {
            this.$toast.fail("您没有访问的权限!");
          }
        }
      } else {
        this.$toast.fail("您没有访问的权限!");
      }
    },
  },
};
</script>
<style lang="less" scoped>
@import "./index.less";
</style>